Clipboard: write() method

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The write() method of the Clipboard interface writes arbitrary data to the clipboard, such as images, fulfilling the returned Promise on completion. This can be used to implement cut and copy functionality.

The method can in theory write arbitrary data (unlike writeText(), which can only write text). Browsers commonly support writing text, HTML, and PNG image data — see browser compatibility for more information.

Syntax

js
write(data)

Parameters

data

An array of ClipboardItem objects containing data to be written to the clipboard.

Return value

A Promise which is resolved when the data has been written to the clipboard. Note that if the underlying OS does not support multiple native clipboard items on the system clipboard, then only the first ClipboardItem in the array is written.

The promise is rejected if the clipboard is unable to write to the clipboard.

Exceptions

NotAllowedError DOMException

Thrown if writing to the clipboard is not allowed.

Security considerations

Writing to the clipboard can only be done in a secure context.

Additional security requirements are covered in the Security consideration section of the API overview topic.

Examples

Write text to the clipboard

This example function replaces the current contents of the clipboard with a specified string when a button is pressed. Note that for this particular case, you could just as readily use Clipboard.writeText().

js
button.addEventListener("click", () => setClipboard("<empty clipboard>"));

async function setClipboard(text) {
  const type = "text/plain";
  const blob = new Blob([text], { type });
  const data = [new ClipboardItem({ [type]: blob })];
  await navigator.clipboard.write(data);
}

The setClipboard() method begins by creating a new a Blob object. This object is required to construct a ClipboardItem object which is sent to the clipboard. The Blob constructor takes in the content we want to copy and its type. This Blob object can be derived from many sources; for example, a canvas.

Next, we create a new ClipboardItem object into which the blob will be placed for sending to the clipboard. The key of the object passed to the ClipboardItem constructor indicates the content type, the value indicates the content. Then write() is called with await. A try..catch block could be used to catch any errors writing the data.

Write canvas contents to the clipboard

This example draws a blue rectangle to the canvas. You can click the rectangle to copy the content of the canvas into the clipboard as an image, and then select another element and paste in the content from the clipboard.

HTML

The HTML just defines our <canvas> element and the <div> element with id target where the canvas image will be pasted.

html
<canvas id="canvas" width="100" height="100"></canvas>

<div id="target">Paste here.</div>
js
const logElement = document.querySelector("#log");
function log(text) {
  logElement.innerText = `${logElement.innerText}${text}\n`;
  logElement.scrollTop = logElement.scrollHeight;
}

JavaScript

First we define an async function to copy a canvas to a blob. This wraps the old callback-style HTMLCanvasElement.toBlob() method into the more intuitive Promise based function.

js
// Async/await method replacing toBlob() callback
async function getBlobFromCanvas(canvas) {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (blob) {
        resolve(blob);
      } else {
        reject(new Error("Canvas toBlob failed"));
      }
    });
  });
}

Next we set up our canvas and add an event listener for the click event.

When you click the blue rectangle the code first checks if the clipboard supports data of type "image/png". If so, the canvas displaying the rectangle is copied into a blob, and then the blob is added to a ClipboardItem and then written to the clipboard.

js
const canvas = document.getElementById("canvas");

// Set up canvas
const ctx = canvas.getContext("2d");
ctx.fillStyle = "cornflowerblue";
ctx.fillRect(0, 0, 100, 100);

canvas.addEventListener("click", copyCanvasContentsToClipboard);
const target = document.getElementById("target");

async function copyCanvasContentsToClipboard() {
  if (ClipboardItem.supports("image/png")) {
    // Copy canvas to blob
    try {
      const blob = await getBlobFromCanvas(canvas);
      // Create ClipboardItem with blob and it's type, and add to an array
      const data = [new ClipboardItem({ [blob.type]: blob })];
      // Write the data to the clipboard
      await navigator.clipboard.write(data);
      log("Copied");
    } catch (error) {
      log(error);
    }
  } else {
    log("image/png is not supported");
  }
}

Note that clipboard support for PNG files is a mandatory part of the specification, so we don't actually need the check using ClipboardItem.supports() above (it always returns true). The check would be more useful in cases where we're fetching an optional file type, or a resource where we don't know the type in advance.

We then define an event listener for paste events on then element where we want to display the clipboard contents as an image. The FileReader API allows us to read the blob using the readAsDataUrl method and create an <img> element with the canvas contents:

js
target.addEventListener("paste", (event) => {
  const items = (event.clipboardData || window.clipboardData).items;
  const blob = items[0].getAsFile();
  const reader = new FileReader();

  reader.addEventListener("load", (event) => {
    const img = new Image();
    img.src = event.target.result;
    target.appendChild(img);
  });

  reader.readAsDataURL(blob);
});

Result

The result is shown below. First click on the blue square, and then select the text "Paste here" and use your OS-specific keyboard combinatations to paste from the clipboard (such as Ctrl+V on Windows).

Specifications

Specification
Clipboard API and events
# dom-clipboard-write

Browser compatibility

BCD tables only load in the browser

See also